const qs = (element) => document.querySelector(element)

axios.defaults.baseURL = 'http://ajax-api.itheima.net'

//========================省=========================
async function fn() {
  const res = await axios.get('/api/province')
  console.log(res);
  const strhtml = res.data.data.map(function (item) {
    return `
      <option value="${item}">${item}</option>
      `
  }).join('')
  qs('.one').innerHTML = '<option value="">--省--</option>' + strhtml
}
fn()

//========================市=========================
async function fn1(pname){
  const ress = await axios.get('/api/city', {
    params: {
      pname
    }
  })
  console.log(ress);
  const gethtml = ress.data.data.map(function (item) {
    return `
         <option value="${item}">${item}</option>
         `
  }).join('')
  qs('.two').innerHTML = '<option value="">--市--</option>' + gethtml
}
fn1()

//========================县=========================
async function fn2(pname,cname){
  const resss = await axios.get('/api/area', {
    params: {
      pname,
      cname
    }
  })
  console.log(resss);
  const posthtml = resss.data.data.map(function (item) {
    return `
         <option value="${item}">${item}</option>
         `
  }).join('')
  qs('.three').innerHTML = '<option value="">--区县--</option>' + posthtml
}
fn2()

//==================省改变，获取对应的市=====================
qs('.one').addEventListener('change', async function () {
  console.log(this.value);
  await fn1(this.value)
  //重新渲染区县数据
  qs('.three').innerHTML = '<option value="">--区县--</option>'
})

//==================市改变，获取对应的县=====================
qs('.two').addEventListener('change', async function () {
  await fn2( qs('.one').value,this.value)
})

//修改头像

qs('.figure-caption').addEventListener('click', function () {
  qs('#upload').click()
})
qs('#upload').addEventListener('change', async function () {
  const file = this.files[0]
  console.log(file);
  if (!file) {
    return
  }
  const fd = new FormData()
  fd.append('avatar', file)
  const res = await axios.post('/api/file', fd)
  console.log(res);
  qs('img').src = res.data.data.url
})

//渲染数据
async function getData(){
  const {data:{data}} = await axios.get("/api/settings")
  console.log(data)
  const {nickname,avatar,province,city,area} = data

  
  qs('[name=nickname]').value = nickname
  
  await fn()
  qs('[name=province]').value = province

  await fn1(province)
  qs('[name=city]').value = city

  await fn2(province,city)
  qs('[name=area]').value = area
  qs('img').src= avatar

// 保存数据 
qs('form').addEventListener('submit',async function(e) {
  e.preventDefault()

  const res =  await axios.put('/api/settings', {
      nickname:qs('[name=nickname]').value,
      province:qs('[name=province]').value,
      city:qs('[name=city]').value ,
      area:qs('[name=area]').value ,
      avatar:qs('img').src

    
  })
    console.log(res);

})
}
getData()



